package com.solarfridge.testclient;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;

/**
 * This class is a wrapper for the HTTP communication with the server.
 * 
 * All requests are made on the calling thread and are blocking. So they should 
 * not be invoked on the Ui thread to avoid ANRs
 * 
 * 
 */
public class HttpServerConnection {
private String mServerUrl;
	
	/**
	 * Simply initializes the object while saving the url for later use. Since http is not
	 * a constant connection protocol, no actualy connection is made at this time.
	 * @param url
	 */
	public HttpServerConnection(String url){
		mServerUrl = url;
	}

	
	/**
	 * Sends a post request to the specified server with the given params.
	 * @param params A list of params
	 * @return The server's response.
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	protected HttpResponse doPost(HttpParamList params) throws ClientProtocolException, IOException{
	    HttpClient httpclient = new DefaultHttpClient();  
	    HttpPost httppost = new HttpPost(mServerUrl);    
	    
        httppost.setEntity(new UrlEncodedFormEntity(params));  
  
        HttpResponse response = httpclient.execute(httppost);  

        return response;
	}
	
	/**
	 * Performs an http get request to the connected server.
	 * @param params
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	protected HttpResponse doGet(HttpParams params) throws ClientProtocolException, IOException{
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(mServerUrl);
		
		httpGet.setParams(params);		
		HttpResponse response = httpClient.execute(httpGet);
		
		return response;
		
	}
	
	public static class HttpParamList extends ArrayList<BasicNameValuePair>{
		private static final long serialVersionUID = -4956388515914610539L;		
	}
}
